package sopt.dev.activity;

import java.io.IOException;
import java.util.List;

import sopt.dev.R;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class GoogleMapActivity extends FragmentActivity {
	GoogleMap googleMap;
	MarkerOptions markerOptions;
	LatLng latLng;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.google_map_activity);

		SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map);

		// 맵 객체 생성
		googleMap = supportMapFragment.getMap();

		// 맵 클릭 리스너
		googleMap.setOnMapClickListener(new OnMapClickListener() {

			@Override
			public void onMapClick(LatLng arg0) {

				// Getting the Latitude and Longitude of the touched location
				latLng = arg0;

				// Clears the previously touched position
				googleMap.clear();

				// Animating to the touched position
				googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

				// Creating a marker
				markerOptions = new MarkerOptions();

				// Setting the position for the marker
				markerOptions.position(latLng);

				// Placing a marker on the touched position
				googleMap.addMarker(markerOptions);

				// Adding Marker on the touched location with address
				new ReverseGeocodingTask(getBaseContext()).execute(latLng);

			}
		});
	}

	// 위도 경도 값을 주소값으로 변환
	private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String> {
		Context mContext;

		public ReverseGeocodingTask(Context context) {
			super();
			mContext = context;
		}

		// Finding address using reverse geocoding
		@Override
		protected String doInBackground(LatLng... params) {
			Geocoder geocoder = new Geocoder(mContext);
			double latitude = params[0].latitude;
			double longitude = params[0].longitude;

			List<Address> addresses = null;
			String addressText = "";

			try {
				addresses = geocoder.getFromLocation(latitude, longitude, 1);
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (addresses != null && addresses.size() > 0) {
				Address address = addresses.get(0);

				addressText = String.format(
						"%s, %s, %s",
						address.getMaxAddressLineIndex() > 0 ? address
								.getAddressLine(0) : "", address.getLocality(),
						address.getCountryName());
			}

			return addressText;
		}

		@Override
		protected void onPostExecute(final String addressText) {
			// Setting the title for the marker.
			// This will be displayed on taping the marker
			markerOptions.title(addressText);

			// Placing a marker on the touched position
			googleMap.addMarker(markerOptions).showInfoWindow();

			googleMap
					.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

						@Override
						public void onInfoWindowClick(Marker arg0) {
							// TODO Auto-generated method stub
							Toast.makeText(GoogleMapActivity.this,
									"선택되었습니다.", Toast.LENGTH_SHORT).show();

							// 값 넘기기
							Intent i = getIntent();
							i.putExtra("addressText", addressText);
							setResult(RESULT_OK, i);
							finish(); // 액티비티 종료

						}
					});

		}

	}

}
